<script setup>
import { ref, onMounted } from "vue";
import { updateUserApi, getUserApi } from "../../api/user";

const formData = ref({
  nickname: "",
  img: "",
  desc: "",
});

const submit = async () => {
  await updateUserApi(formData.value);
  uni.navigateBack();
};

const getUserInfo = async () => {
  const { nickName, img, desc } = await getUserApi();

  formData.value = { nickname: nickName, img, desc };
};

const chooseImg = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      uni.uploadFile({
        url: "http://localhost:3000/uploads/img",
        filePath: res.tempFilePaths[0],
        name: "file",
        success: (res) => {
          console.log(res);
          const { path } = JSON.parse(res.data);
          formData.value.img = path;
        },
      });
    },
  });
};

onMounted(() => {
  getUserInfo();
});
</script>

<template>
  <view class="userInfo">
    <view class="userInfo__avatar">
      <image
        @click="chooseImg"
        :src="`http://localhost:3000/${formData.img}`"
        mode="scaleToFill"
      />
    </view>
    <view class="userInfo__info">
      <uni-forms-item label="昵称" prop="nickname">
        <uni-easyinput v-model="formData.nickname" placeholder="请输入昵称" />
      </uni-forms-item>
      <uni-forms-item label="个人描述" prop="desc">
        <uni-easyinput
          type="textarea"
          v-model="formData.desc"
          placeholder="请输入个人描述"
        />
      </uni-forms-item>

      <view class="userInfo__submit">
        <button type="primary" @click="submit">修改</button>
      </view>
    </view>
  </view>
</template>
